import { ignoreTimeZone, messages } from 'share/common';
import React, { Component } from 'react';
import { Icon } from 'antd';
import 'styles/expense/expense-body.scss';
import ExpenseService from '../expense-service';
import baseService from 'share/base.service';
import menuRoute from 'routes/menuRoute';
import errorMessage from 'share/errorMessage';
import { connect } from 'react-redux';
import infoImg from 'images/expense-detail/ingo.svg';
import Annotate from 'components/template/annotate';
import LocationMap from 'components/map';
import WayPointEdit from '../../mileage-subsidy-expense/components/way-point-edit';
import WayPointMap from '../../mileage-subsidy-expense/components/way-point-map';
import shallowEqual from '../component/shallowEqual';
import moment from 'moment'


@connect(mapStateToProps)
class ExpenseField extends Component {

  constructor(props, context) {
    super(props, context);
    this.state = {
      ...this.initData(context)
    };
  }

  static contextTypes = {
    annotates: React.PropTypes.array,
    fieldsData: React.PropTypes.array,
    currentExpense: React.PropTypes.object,
    isWaitForAudit: React.PropTypes.bool,
    expenseReport: React.PropTypes.object,
  };

  shouldComponentUpdate(nextProps, nextState, nextContext) {
    return !shallowEqual(this.props, nextProps) ||
      !shallowEqual(this.state, nextState) ||
      !shallowEqual(this.context, nextContext);
  }

  componentWillReceiveProps(nextProps,nextContext) {
    nextProps.randomHash !== this.props.randomHash && this.setState(this.initData(nextContext));
  }

  initData = (context) => {
    const { annotates } = context;
    return {
      annotates: annotates
    };
  };

  getFieldValue = (params) => {
    const { field = {}, withTime, nowExpense, skipApplication, isSubsidyType } = params;
    const { fieldType, value, messageKey, showValue, dataIndex } = field;
    if (!value) {
      return '-';
    }

    function START_DATE_AND_END_DATE() {
      let result = JSON.parse(value);
      let formatData = (withTime && isSubsidyType) ? 'YYYY-MM-DD HH:mm' : 'YYYY-MM-DD';
      return (
        <span>
            {moment(ignoreTimeZone(result.startDate))
              .format(formatData)}
          {` ~ `}
          {moment(ignoreTimeZone(result.endDate))
            .format(formatData)}
          {` `}
          </span>
      );
    }

    function AssistValue(props) {
      const { value, assist } = props;
      return (
        <div>
          {value}
          <span className="expense-body-field-desc">{assist}</span>
        </div>
      );
    }

    const FIELD_VALUE_OBJ = {
      'ASSOCIATE_APPLICATION': () => {
        return <a onClick={() => skipApplication(value)}><Icon fieldType="link"/>&nbsp;{value}
        </a>;
      },
      'DATE': () => {
        return new Date(value).format('yyyy-MM-dd');
      },
      'MONTH': () => {
        return new Date(value).format('yyyy-MM');
      },
      'DATETIME': () => {
        return new Date(value).format('yyyy-MM-dd hh:mm:ss');
      },
      'BOOLEAN': () => {
        return value === 'true' ? messages('common.yes')/*是*/ : messages('common.no')/*否*/;
      },
      'PROMPT_KEY': () => {
        return <div className="field-prompt-container">{field.placeholder}</div>;
      },
      'GPS': () => {
        return JSON.parse(value).address ? <LocationMap.Text location={JSON.parse(value)}/> : '-';
      },
      'START_DATE_AND_END_DATE': () => {
        return JSON.parse(value) ? START_DATE_AND_END_DATE() : '-';
      },
      'TEXT': () => {
        if (messageKey === 'dateCombined' && JSON.parse(value)) {
          return JSON.parse(value) ? START_DATE_AND_END_DATE() : '-';
        } else {
          return value;
        }
      }
    };

    const NOT_FIELD_VALUE_OBJ = {
      viaPoints: () => (
        <WayPointEdit
          value={value}
          annotateDisabled
          disabled
          nowExpense={nowExpense}/>
      ),
      wayPointMap: () => (<WayPointMap record={value}/>),
      mileageUnit: () => (<AssistValue {...value}/>)

    };

    return FIELD_VALUE_OBJ[fieldType] ? FIELD_VALUE_OBJ[fieldType]() : NOT_FIELD_VALUE_OBJ[dataIndex] ? NOT_FIELD_VALUE_OBJ[dataIndex]() : showValue;
  };


  //跳转申请单
  skipApplication = async (applicationNumber) => {
    const res = await baseService.queryApplicationInfo(applicationNumber, this.props.company.tenantId);
    try {
      window.open(menuRoute.getRouteItem('request-detail', 'key')
        .url
        .replace(':formOID', res.data.formOID)
        .replace(':applicationOID', res.data.applicationOID));
    }
    catch (e) {
      errorMessage(e.response);
    }
  };

  handleAnnotate = async () => {
    const { currentExpense: { invoiceOID } } = this.context;
    const annotates = await ExpenseService.getAnnotate(invoiceOID);
    this.setState({ annotates });
  };

  render() {
    const { loginUser } = this.props;
    const { annotates } = this.state;
    const { fieldsData, currentExpense, isWaitForAudit, expenseReport: { withTime } } = this.context;
    return (
      <section className="expense-body">
        <div className="expense-body-title">
          <img src={infoImg} alt="info"/>
          <span className="expense-body-lf">{messages('common.baseInfo')/*基本信息*/}</span>
        </div>
        {
          fieldsData.map(item =>
            <Annotate
              params={
                !item.isNotField ? {
                    typeName: 'INVOICE',
                    entityID: currentExpense.id,
                    target: {
                      type: 'fieldOID',
                      key: item.fieldOID
                    }
                  }
                  : {
                    typeName: 'INVOICE',
                    entityID: currentExpense.id,
                    target: {
                      type: item.key,
                      key: item.speKey
                    }
                  }}
              onChange={this.handleAnnotate}
              disabled={!isWaitForAudit}
              annotateList={ExpenseService.getAnnotateList(item.fieldOID || item.speKey || item.key, annotates, loginUser)}
            >
              <div
                className={`expense-body-field ${isWaitForAudit ? 'expense-item-annotate' : ''}`}>
                <div className="expense-body-field-name">{item.name}</div>
                <div className='expense-body-field-value'>
                  {
                    this.getFieldValue({
                      field: item,
                      withTime,
                      nowExpense: currentExpense,
                      skipApplication: this.skipApplication,
                      isSubsidyType: currentExpense.expenseTypeSubsidyType === 1
                    })
                  }
                </div>
              </div>
            </Annotate>
          )
        }
      </section>
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    loginUser: state.login.loginUser,
    profile: state.login.profile,
    options: state.login.options,
  };
}

ExpenseField.propTypes = {};

export default ExpenseField;
